<template>
  <div>
    <!-- 顶部 -->
    <el-card>
      <el-row>
        <el-col :span="7" class="top_input">
          <label>车牌号：</label>
          <el-input
            clearable
            v-model="searchModel.plateNumber"
            placeholder="请输入车牌号"
          ></el-input>
        </el-col>
        <el-col :span="7" class="top_input">
          <label><div>状态：</div></label>
          <el-select
            v-model="searchModel.status"
            clearable
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>

      <div style="margin-left: 5px">
        <el-button type="primary" plain size="small" @click="getCarList()"
          >搜索</el-button
        >
        <el-button type="primary" plain size="small" @click="addCar()"
          >添加车辆</el-button
        >
      </div>
    </el-card>

    <!-- 用户展示区域 -->
    <el-card class="box-card">
      <el-table :data="carList" style="width: 100%" v-loading="loading">
        <el-table-column label="行驶证图片" width="180">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.licenseImgUrl"
              :preview-src-list="[scope.row.licenseImgUrl]"
              v-if="scope.row.licenseImgUrl"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="plateNumber" label="车牌号" width="180">
        </el-table-column>
        <el-table-column prop="model" label="车辆品牌/车型" width="180">
        </el-table-column>
        <el-table-column prop="vehicle_type" label="车辆类型">
        </el-table-column>
        <el-table-column prop="seatCount" label="座位数"> </el-table-column>
        <el-table-column prop="color" label="车身颜色"> </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">
              <el-tag type="success" effect="dark"> 已启用 </el-tag>
            </span>
            <span v-if="scope.row.status == 1">
              <el-tag type="warning" effect="dark"> 出车中 </el-tag>
            </span>
            <span v-if="scope.row.status == 2">
              <el-tag type="danger" effect="dark"> 维修中 </el-tag>
            </span>
          </template>
        </el-table-column>

        <el-table-column width="220" label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-button type="text" size="small" @click="edit(scope.row.id)"
                  >编辑</el-button
                ></el-col
              >
              <el-col :span="12"
                ><el-button
                  type="text"
                  size="small"
                  @click="openDrawer(scope.row.id)"
                  >查看详情</el-button
                ></el-col
              >
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-button
                  type="text"
                  size="small"
                  @click="openImgDig(scope.row.id)"
                  >上传行驶证照片</el-button
                >
              </el-col>
              <el-col :span="12"
                ><el-button
                  type="text"
                  size="small"
                  style="color: red"
                  @click="del(scope.row.id)"
                  >删除</el-button
                ></el-col
              >
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-size="searchModel.pageSize"
      layout="total,  prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 汽车信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="carfrom" :model="carFrom" label-width="80px" :rules="rules">
        <el-form-item label="车牌号" prop="plateNumber" label-width="110px">
          <el-input
            v-model="carFrom.plateNumber"
            placeholder="请输入车牌号"
          ></el-input>
        </el-form-item>
        <el-form-item label="车辆品牌/车型" prop="model" label-width="110px">
          <el-input
            v-model="carFrom.model"
            placeholder="请输入车辆品牌/车型"
          ></el-input>
        </el-form-item>

        <el-form-item label="车辆类型" prop="vehicleType" label-width="110px">
          <el-input
            v-model="carFrom.vehicleType"
            placeholder="请输入车辆类型"
          ></el-input>
        </el-form-item>
        <el-form-item label="座位数" prop="seatCount" label-width="110px">
          <el-input-number
            v-model="carFrom.seatCount"
            :min="1"
            :max="100"
            placeholder="请输入座位数"
            style="width: 220px"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="车身颜色" prop="color" label-width="110px">
          <el-input
            v-model="carFrom.color"
            placeholder="请输入车身颜色"
          ></el-input>
        </el-form-item>
        <el-form-item label="购置日期" prop="purchaseDate" label-width="110px">
          <el-date-picker
            v-model="carFrom.purchaseDate"
            type="date"
            placeholder="选择购置日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="保险到期日"
          prop="insuranceExpiry"
          label-width="110px"
        >
          <el-date-picker
            v-model="carFrom.insuranceExpiry"
            type="date"
            placeholder="选择保险到期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="年检到期日"
          prop="annualCheckExpiry"
          label-width="110px"
        >
          <el-date-picker
            v-model="carFrom.annualCheckExpiry"
            type="date"
            placeholder="选择年检到期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="燃油类型" prop="fuelType" label-width="110px">
          <el-input
            v-model="carFrom.fuelType"
            placeholder="请输入燃油类型"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="110px">
          <el-select v-model="carFrom.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remarks" label-width="110px">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
            v-model="carFrom.remarks"
          ></el-input>
        </el-form-item>

        <el-form-item align="right">
          <el-button type="primary" @click="editCar()">确定</el-button>
          <el-button @click="close()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 上传行驶证图片对话框 -->
    <el-dialog
      title="行驶证图片"
      :visible.sync="dialogVisiblePhoto"
      width="30%"
      :before-close="closeImgDig"
    >
      <el-upload
        action="http://localhost:9999/file/upload"
        :headers="{ Authorization: token }"
        :file-list="fileList"
        :limit="1"
        :on-exceed="handleExceed"
        list-type="picture"
        accept="image/jpeg,image/jpg,image/png"
        :on-remove="handleRemove"
        :on-success="handleImgSuccess"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeImgDig()">取 消</el-button>
        <el-button type="primary" @click="uploadImg()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 车辆详情抽屉 -->
    <el-drawer
      title="车辆详情"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
      size="50%"
    >
      <el-card style="padding: 10px">
        <el-row>
          <el-col :span="24">
            <div style="margin: 5px"><strong>行驶证图片：</strong></div>
            <el-image
              v-if="
                this.carFrom.licenseImgUrl !== undefined &&
                this.carFrom.licenseImgUrl !== null
              "
              style="width: 300px; height: 300px"
              :src="this.carFrom.licenseImgUrl"
              :preview-src-list="[this.carFrom.licenseImgUrl]"
            >
            </el-image>
            <div v-else style="width: 300px; height: 300px">待上传</div>
          </el-col>
        </el-row>

        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>车牌号：</label>
            <span>{{ this.carFrom.plateNumber }}</span></el-col
          >
          <el-col :span="12">
            <label>车辆品牌/车型：</label>
            <span>{{ this.carFrom.model }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>车辆类型：</label>
            <span>{{ this.carFrom.vehicleType }}</span></el-col
          >
          <el-col :span="12">
            <label>座位数：</label>
            <span>{{ this.carFrom.seatCount }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>车身颜色：</label>
            <span>{{ this.carFrom.color }}</span></el-col
          >
          <el-col :span="12">
            <label>购置日期：</label>
            <span>{{ this.carFrom.purchaseDate }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>保险到期日：</label>
            <span>{{ this.carFrom.insuranceExpiry }}</span></el-col
          >
          <el-col :span="12">
            <label>年检到期日：</label>
            <span>{{ this.carFrom.annualCheckExpiry }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>燃油类型：</label>
            <span>{{ this.carFrom.fuelType }}</span></el-col
          >
          <el-col :span="12">
            <label>当前里程：</label>
            <span>{{ this.carFrom.mileage }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>车辆位置：</label>
            <span>{{ this.carFrom.location }}</span></el-col
          >
          <el-col :span="12">
            <label>状态：</label>
            <span v-if="this.carFrom.status == 0">
              <el-tag type="success" effect="dark"> 已启用 </el-tag>
            </span>
            <span v-if="this.carFrom.status == 1">
              <el-tag type="warning" effect="dark"> 出车中 </el-tag>
            </span>
            <span v-if="this.carFrom.status == 2">
              <el-tag type="danger" effect="dark"> 维修中 </el-tag>
            </span>
          </el-col>
        </el-row>
        <el-row style="margin: 10px">
          <label>备注：</label>
          <span>{{ this.carFrom.remarks }}</span>
        </el-row>
      </el-card>

      <el-card style="padding: 10px">
        <div style="margin: 5px"><strong>司机信息</strong></div>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>司机ID：</label>
            <span>{{ this.driverFrom.driverId }}</span></el-col
          >
          <el-col :span="12">
            <label>驾照类型：</label>
            <span>{{ this.driverFrom.licenseType }}</span></el-col
          >
        </el-row>
        <el-row style="margin: 10px">
          <el-col :span="12">
            <label>司机名称：</label>
            <span>{{ this.driverFrom.driverName }}</span></el-col
          >
          <el-col :span="12">
            <label>驾龄：</label>
            <span>{{ this.driverFrom.drivingExperience }}</span></el-col
          >
        </el-row>
      </el-card>
    </el-drawer>
  </div>
</template>

<style>
.top_input {
  margin: 4px;
}
</style>

<script>
import carApi from "@/api/car";
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
  data() {
    return {
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },

      total: 0,

      carFrom: {},
      driverFrom: {},

      carList: [],

      // 对话框
      dialogVisible: false,

      title: "",

      // 车辆状态
      statusOptions: [
        {
          value: 0,
          label: "已启用",
        },
        {
          value: 1,
          label: "出车中",
        },
        { value: 2, label: "维修中" },
      ],

      // rule
      rules: {
        plateNumber: [
          { required: true, message: "请输入车牌号", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        model: [
          { required: true, message: "请输入车辆品牌/车型", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        vehicleType: [
          { required: true, message: "请输入车辆类型", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        seatCount: [
          { required: true, message: "座位数不能为空" },
          { type: "number", message: "座位数必须为数字值" },
        ],
        color: [
          { required: true, message: "请输入车身颜色", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],

        fuelType: [
          { required: true, message: "请输入燃油类型", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        remarks: [
          {
            min: 1,
            max: 255,
            message: "长度在 1 到 255 个字符",
            trigger: "blur",
          },
        ],
      },

      // 行驶证图片
      dialogVisiblePhoto: false,
      token: "",
      fileList: [],

      // 抽屉
      drawer: false,

      loading: false,
    };
  },

  methods: {
    getCarList() {
      this.loading = true;
      carApi.getCarList(this.searchModel).then((res) => {
        this.carList = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },

    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getCarList();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.close();
        })
        .catch((_) => {});
    },

    handleCloseDrawer() {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.closeDrawr();
        })
        .catch((_) => {});
    },

    openDrawer(id) {
      this.loading = true;
      carApi.getCarById(id).then((res) => {
        this.carFrom = res.data.carInfo;
        this.driverFrom.driverId = res.data.driverId;
        this.driverFrom.driverName = res.data.driverName;
        this.driverFrom.drivingExperience = res.data.drivingExperience;
        this.driverFrom.licenseType = res.data.licenseType;
        this.drawer = true;
        this.loading = false;
      });
    },

    closeDrawr() {
      this.drawer = false;
      this.carFrom = {};
    },

    close() {
      this.dialogVisible = false;
      this.carFrom = {};

      // 清空验证
      this.$refs["carfrom"].resetFields();
    },

    open() {
      this.dialogVisible = true;
    },

    addCar() {
      this.carFrom = {};
      this.title = "添加车辆";
      this.open();
    },

    editCar() {
      this.$refs["carfrom"].validate((valid) => {
        if (valid) {
          this.loading = true;
          carApi.saveCar(this.carFrom).then((res) => {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.getCarList();

            this.close();
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },

    edit(id) {
      // 查询车辆信息
      carApi.getCarById(id).then((res) => {
        this.carFrom = res.data.carInfo;
        this.title = "编辑车辆";
        this.open();
      });
    },

    del(id) {
      this.$confirm("确认删除？").then((_) => {
        this.loading = true;
        carApi
          .deleteByid(id)
          .then((res) => {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.getCarList();
            this.loading = false;
          })
          .finally(() => {
            this.loadling = false;
          });
      });
    },

    handleExceed() {
      this.$message.warning(`限制上传 1 个文件`);
    },

    uploadImg() {
      if (this.fileList.length == 0) {
        this.$message.warning(`请上传图片`);
        return;
      }
      this.carFrom.licenseImgUrl = this.fileList[0].url;
      this.loading = true;
      carApi.updateById(this.carFrom).then((res) => {
        this.$message({
          message: res.message,
          type: "success",
        });
        this.getCarList();
        this.closeImgDig();
        this.loading = false;
      });
    },

    handleBeforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
    },
    handleImgSuccess(response) {
      this.fileList.push({
        name: response.message,
        url: `http://localhost:9999/file/download?name=${response.message}`,
      });
    },
    handleRemove() {
      this.fileList = [];
    },

    openImgDig(id) {
      this.fileList = [];
      this.loading = true;
      carApi.getCarById(id).then((res) => {
        console.log(res.data.licenseImgUrl);
        if (
          res.data.licenseImgUrl != undefined &&
          res.data.licenseImgUrl != ""
        ) {
          this.fileList.push({
            name: res.data.plateNumber,
            url: res.data.licenseImgUrl,
          });
        }
        this.carFrom = res.data.carInfo;

        this.dialogVisiblePhoto = true;
        this.loading = false;
      });
    },
    closeImgDig() {
      this.dialogVisiblePhoto = false;
      this.carFrom = {};
      this.fileList = [];
    },
  },

  watch: {
    dialogVisible(newVal) {
      if (!newVal) {
        this.$refs["carfrom"].resetFields();
      }
    },
  },

  created() {
    this.getCarList();

    this.token = getToken();
  },
};
</script>
